#pragma warning(disable:4996)
#pragma warning(disable:6031)
#pragma warning(disable:6011)

/*
example 7.3 Convert the following infix
expression into postfix expression using the
algorithm given in Fig. 7.22.
(a) A - (B / C + (D % E * F) / G)* H
(b) A - (B / C + (D % E * F) / G)* H)
*/

namespace Y190626_eval_of_arithmetic_expressions {
int main();

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX 100
typedef char ElementType;
ElementType st[MAX];
int top = -1;
ElementType pop();
void push(ElementType);

ElementType pop() {
	char val = ' ';
	if (top == -1)
		printf("\n Stack Underflow");
	else
		val = st[top--];
	return val;
}
int getPriority(char op)
{
	if (op == '/' || op == '*' || op == '%')
		return 1;
	else if (op == '+' || op == '-')
		return 0;
}
void push(ElementType c) {
	if (top == (MAX - 1))
		printf("Stack Overflow\n");
	else
	{
		top = top + 1;
		st[top] = c;
	}
}

void InfixtoPostfix(char source[], char target[])
{
 	int i = 0, j = 0;
	char temp;
	strcpy(target, "");
	while (source[i] != '\0')
	{
		if (source[i] == '(')
		{
			push(source[i++]);
		}
		else if (source[i] == ')')
		{
			while ((top != -1) && (st[top] != '('))
			{
				target[j++] = pop();
			}
			if (top == -1)
			{
				printf("\n INCORRECT EXPRESSION");
				exit(1);
			}
			temp = pop();//remove left parenthesis
			i++;
		}
		else if (isdigit(source[i]) || isalpha(source[i]))
		{
			target[j++] = source[i++];
		}
		else if (source[i] == '+' || source[i] == '-' || source[i] == '*' || source[i] == '/' || source[i] == '%')
		{
			while ((top != -1) && (st[top] != '(') && (getPriority(st[top]) >= getPriority(source[i])))
			{
				target[j++] = pop();
			}
			push(source[i++]);
		}
		else
		{
			printf("\n INCORRECT ELEMENT IN EXPRESSION");
			exit(1);
		}
	}
	while ((top != -1) && (st[top] != '('))
	{
		target[j++] = pop();
	}
	target[j] = '\0';
}

int main() {
	char infix[100], postfix[100];
	printf("\n Enter any infix expression : ");
	gets_s(infix);
	strcpy(postfix, "");
	InfixtoPostfix(infix, postfix);
	printf("\n The corresponding postfix expression is : ");
	puts(postfix);
	return 0;
}

}

int main_Y190626_eval_of_arithmetic_expressions()
{
	return Y190626_eval_of_arithmetic_expressions::main();
}